package com.example.glgk.utils;

import com.example.glgk.dto.QueryEscalation;
import com.example.glgk.dto.gather.DeptEscalationDataDto;
import com.example.glgk.dto.gather.HeaderDataDto;
import com.example.glgk.excel.ExcelDto;
import com.example.glgk.excel.ExcelField;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static org.apache.commons.lang3.StringUtils.isNumeric;

/**
 * @author lxk
 * <p>测试动态列+多级表头导出Excel</p>
 */
public class ExcelUtilsPlus {


    static private final int HEAD_ROW_COUNT = 3;

    public static <T> void export(List<T> dataList, Class clazz, HttpServletResponse response, QueryEscalation queryEscalation) {
        //获取传入的实体类的带注解,确定文件名
        ExcelDto export = (ExcelDto) clazz.getAnnotation(ExcelDto.class);
        String fileName;
        if (export == null || StringUtils.isEmpty(export.fileName())) {
            fileName = "exportExcel.xls";
        } else {
            fileName = export.fileName() + ".xls";
        }
        OutputStream os = null;
        try {
            os = getBufferedOutputStream(fileName, response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        export(dataList, clazz, os, queryEscalation);
    }

    public static <T> void exportDeptData(List<T> dataList, Class clazz, HttpServletResponse response, QueryEscalation queryEscalation) {
        //获取传入的实体类的带注解,确定文件名
        ExcelDto export = (ExcelDto) clazz.getAnnotation(ExcelDto.class);
        String fileName;
        if (export == null || StringUtils.isEmpty(export.fileName())) {
            fileName = "exportExcel.xls";
        } else {
            fileName = export.fileName() + ".xls";
        }
        OutputStream os = null;
        try {
            os = getBufferedOutputStream(fileName, response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        exportData(dataList, clazz, os, queryEscalation);
    }

    public static <T> void exportData(List<T> dataList, Class clazz, OutputStream os, QueryEscalation queryEscalation) {
        //所有允许导出的字段
        Map<Integer, Field> fieldMap = new HashMap<>();
        //一级表头
        List<String> dynamicKeys = new ArrayList<>();
        //二级表头 todo 判断是否存在多级表头的话，这里应该递归来判断，暂时写死
        List<String> subordinateNames = new ArrayList<>();

        //创建一个Excel工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //建立表
        HSSFSheet hssfsheet = workbook.createSheet();

        //表格样式
        HSSFCellStyle cellStyle = getBasicCellStyle(workbook);

        hssfsheet.setDefaultRowHeight((short) (20 * 20));

        //所有需要导出的一级表头字段 二级表头字段
        Map<Integer, String> colNames = new HashMap<>();
        Map<Integer, String> subColNames = new HashMap<>();
        //所有允许导出的字段
        int index = 0;
        int maxSize = 0;
        for (Field field : clazz.getDeclaredFields()) {
            //如果字段带有ExcelField注解，表示需要导出
            if (field.isAnnotationPresent(ExcelField.class)) {
                ExcelField excelField = field.getAnnotation(ExcelField.class);
//                dynamicKeys.add(excelField.colName());
                //存一级表头索引和表头名
                colNames.put(excelField.index(), excelField.colName());
                //这里是把前三的固定列存到需要导出的字段里面
                fieldMap.put(excelField.index(), field);
                index++;
            } else if (field.getType() == Map.class) {
                //动态列导出 key是一级表头 value就是二级表头
                ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
                Class<?> mapKeyType = (Class<?>) parameterizedType.getActualTypeArguments()[0];
                Class<?> mapValueType = (Class<?>) parameterizedType.getActualTypeArguments()[1];
                if (mapKeyType == String.class) {
                    // 这里就要将数据集合里面存储的实际的key作为需要被设置导出的表头，而不是把这个map作为表头
                    field.setAccessible(true);
                    Map<String, ?> dynamicColumnsValue = null;
                    try {
                        T t = dataList.get(0);
                        dynamicColumnsValue = (Map<String, ?>) field.get(t);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    // 将实际的 Map 的 key 存储到 dynamicKeys 中
                    dynamicKeys.addAll(dynamicColumnsValue.keySet());
                    fieldMap.put(fieldMap.size(), field);
                    maxSize = dynamicColumnsValue.keySet().size();
                }
                //其实这里可以写个基类，做二级表头的可以继承一下
                if (mapValueType == HeaderDataDto.class) {
                    //二级表头
                    field.setAccessible(true);
                    for (Field valueField : mapValueType.getDeclaredFields()) {
                        if (valueField.isAnnotationPresent(ExcelField.class)) {
                            ExcelField excelField = valueField.getAnnotation(ExcelField.class);
                            subordinateNames.add(excelField.colName());
                            hssfsheet.setColumnWidth(index, excelField.colWidth() * 20);
                        }
                    }

                }
            }

        }
        int size = colNames.size();
        for (int i = 0; i < dynamicKeys.size(); i++) {
            colNames.put(size + i, dynamicKeys.get(i));
        }
        for (int i = 0; i < subordinateNames.size(); i++) {
            subColNames.put(size + i, subordinateNames.get(i));
        }
        //看看有多少个日期列 那就要往subColNames塞对应的组的同比值，环比值等表头
        //有几个时间列
        int timeLines = colNames.size() - 5;
        for (int i = 0; i < timeLines; i++) {
            for (int j = 0; j < 3; j++) {
                //求出最大索引
                OptionalInt max = subColNames.keySet().stream()
                        .mapToInt(Integer::intValue)
                        .max();
                int maxIndex = max.getAsInt();
                subColNames.put(++maxIndex, subordinateNames.get(j));
            }
        }

        //创建标题行（表头）
        for (int i = 0; i < dynamicKeys.size(); i++) {
            colNames.put(size + i, dynamicKeys.get(i));
        }
        createHeadRow(workbook, hssfsheet, colNames);
        //表格样式
        // 创建大表头行
        HSSFRow a = hssfsheet.createRow(0);
        a.setHeightInPoints((short) 30);
        HSSFCell headerCell = a.createCell(0);
        // 创建字体样式
        HSSFFont font = workbook.createFont();
        font.setBold(true); // 设置为加粗
        font.setFontHeightInPoints((short) 22); // 设置字体大小
        HSSFCellStyle style = workbook.createCellStyle();
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        headerCell.setCellStyle(style);

        setTitle(queryEscalation.getTimes(), headerCell);
        // 合并大表头单元格
        hssfsheet.addMergedRegion(new CellRangeAddress(0, 0, 0, subColNames.size()+fieldMap.size() - 2));

        // 创建小字行
        HSSFRow subtitleRow = hssfsheet.createRow(1);
        HSSFCell subtitleCell = subtitleRow.createCell(0);
        subtitleCell.setCellValue("编制单位：南京鼓楼医院");
        // 合并小字单元格
        hssfsheet.addMergedRegion(new CellRangeAddress(1, 1, 0, subColNames.size()+fieldMap.size() - 2));

        // 设置第一行表头
        Row headerRow = hssfsheet.createRow(2);
        boolean flag = false;
        int maxRowIndex = 0;
        int aaa = 0;
        int bbb = 0;
        for (Integer colIndex : colNames.keySet()) {
            String colName = colNames.get(colIndex);
            //如果colIndex>=4，那么这个表头就要占三个单元格
            Cell cell = null;
            if (flag) {
                bbb++;
                cell = headerRow.createCell(colIndex + 2 * bbb);
            } else {
                cell = headerRow.createCell(colIndex);
            }
            cell.setCellValue(colName);
            if (colIndex >= 5) {
                //时间列占三格
                //区分第一次和后续
                if (flag) {
                    aaa++;
                    hssfsheet.addMergedRegion(new CellRangeAddress(2, 2, colIndex + 2 * aaa, colIndex + 2 * (aaa + 1)));
                    maxRowIndex = colIndex + 2 * (aaa + 1);
                } else {
                    hssfsheet.addMergedRegion(new CellRangeAddress(2, 2, colIndex, colIndex + 2));
                    maxRowIndex = colIndex + 2 * (aaa + 1);
                }
                flag = true;
            }
        }


        // 设置第二行表头 这里循环能不能记录一下第一行colIndex+2的最大值？？
        Row subHeaderRow = hssfsheet.createRow(3);
        for (int colIndex = 0; colIndex <= maxRowIndex; colIndex++) {
            String colName = subColNames.get(colIndex) == null ? "" : subColNames.get(colIndex);
            //如果colIndex>=4，那么这个表头就要占三个单元格
            Cell cell = subHeaderRow.createCell(colIndex);
            //对于非日期列，我们只需要第一行同列合并即可
            if (colIndex < 5) {
                hssfsheet.addMergedRegion(new CellRangeAddress(2, 3, colIndex, colIndex));
            }
            cell.setCellValue(colName);
        }

        HSSFRow hssfRow = null;
        //接下来就是导出数据
        int i = 0;
        if (!CollectionUtils.isEmpty(dataList)) {
            for (Object obj : dataList) {
                hssfRow = hssfsheet.createRow(hssfsheet.getLastRowNum() + 1);
                int dynamicColumnCount = dynamicKeys.size() * 3; // 每个动态列有三个字段
                int totalColumnCount = 5 + dynamicColumnCount; // 固定列 + 动态列的总数

                HSSFCellStyle basicCellStyle = getBasicCellStyle(workbook);
                for (int j = 0; j < totalColumnCount; j++) {
                    if (j == 0) {
                        // 项目列需要靠左
                        basicCellStyle.setAlignment(HorizontalAlignment.LEFT);
                    }

                    Object value = null;
                    try {
                        if (j < 5) {
                            // 对于固定的前三列，直接取值
                            Field field = fieldMap.get(j);
                            field.setAccessible(true);
                            value = field.get(obj);
                        } else {
                            // 对于动态列，需要特殊处理
                            int dynamicIndex = (j - 5) / 3; // 计算当前动态列的索引
                            String currentDate = dynamicKeys.get(dynamicIndex); // 获取当前动态列对应的日期
                            OptionalInt max = fieldMap.keySet().stream()
                                    .mapToInt(Integer::intValue)
                                    .max();
                            int maxIndex = max.getAsInt();
                            Map<String, HeaderDataDto> dynamicColumnMap = (Map<String, HeaderDataDto>) fieldMap.get(maxIndex).get(obj); // 获取动态列字段的值
                            HeaderDataDto headerDataDto = dynamicColumnMap.get(currentDate); // 获取对应日期的 HeaderDataDto 对象
                            // 根据当前列的偏移量来确定具体是指标值、同比值还是环比值
                            switch ((j - 5) % 3) {
                                case 0:
                                    value = headerDataDto.getIndicator();
                                    break;
                                case 1:
                                    value = headerDataDto.getYoyValue();
                                    break;
                                case 2:
                                    value = headerDataDto.getMomValue();
                                    break;
                                default:
                                    // 可选的其他情况处理
                                    break;
                            }
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }

                    hssfsheet.autoSizeColumn(j);
                    if (j == 0) {
                        setCellValue(value, hssfRow, basicCellStyle, j);
                    } else {
                        setCellValue(value, hssfRow, cellStyle, j);
                    }
                }
                i++;
            }
        }


        // 导出到文件
        try {
            workbook.write(os);
            os.flush();
            os.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(111111);
    }


    /**
     * 暂时都是写死的，没做通用性
     *
     * @param dataList
     * @param clazz
     * @param os
     */
    public static <T> void export(List<T> dataList, Class clazz, OutputStream os, QueryEscalation queryEscalation) {
        //所有允许导出的字段
        Map<Integer, Field> fieldMap = new HashMap<>();
        //一级表头
        List<String> dynamicKeys = new ArrayList<>();
        //二级表头 todo 判断是否存在多级表头的话，这里应该递归来判断，暂时写死
        List<String> subordinateNames = new ArrayList<>();

        //创建一个Excel工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //建立表
        HSSFSheet hssfsheet = workbook.createSheet();

        //表格样式
        HSSFCellStyle cellStyle = getBasicCellStyle(workbook);

        hssfsheet.setDefaultRowHeight((short) (20 * 20));

        //所有需要导出的一级表头字段 二级表头字段
        Map<Integer, String> colNames = new HashMap<>();
        Map<Integer, String> subColNames = new HashMap<>();
        //所有允许导出的字段
        int index = 0;
        int maxSize = 0;
        for (Field field : clazz.getDeclaredFields()) {
            //如果字段带有ExcelField注解，表示需要导出
            if (field.isAnnotationPresent(ExcelField.class)) {
                ExcelField excelField = field.getAnnotation(ExcelField.class);
//                dynamicKeys.add(excelField.colName());
                //存一级表头索引和表头名
                colNames.put(excelField.index(), excelField.colName());
                //这里是把前三的固定列存到需要导出的字段里面
                fieldMap.put(excelField.index(), field);
                index++;
            } else if (field.getType() == Map.class) {
                //动态列导出 key是一级表头 value就是二级表头
                ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
                Class<?> mapKeyType = (Class<?>) parameterizedType.getActualTypeArguments()[0];
                Class<?> mapValueType = (Class<?>) parameterizedType.getActualTypeArguments()[1];
                if (mapKeyType == String.class) {
                    // 这里就要将数据集合里面存储的实际的key作为需要被设置导出的表头，而不是把这个map作为表头
                    field.setAccessible(true);
                    Map<String, ?> dynamicColumnsValue = null;
                    try {
                        T t = dataList.get(0);
                        dynamicColumnsValue = (Map<String, ?>) field.get(t);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    // 将实际的 Map 的 key 存储到 dynamicKeys 中
                    dynamicKeys.addAll(dynamicColumnsValue.keySet());
                    fieldMap.put(fieldMap.size(), field);
                    maxSize = dynamicColumnsValue.keySet().size();
                }
                //其实这里可以写个基类，做二级表头的可以继承一下
                if (mapValueType == HeaderDataDto.class) {
                    //二级表头
                    field.setAccessible(true);
                    for (Field valueField : mapValueType.getDeclaredFields()) {
                        if (valueField.isAnnotationPresent(ExcelField.class)) {
                            ExcelField excelField = valueField.getAnnotation(ExcelField.class);
                            subordinateNames.add(excelField.colName());
                            hssfsheet.setColumnWidth(index, excelField.colWidth() * 20);
                        }
                    }

                }
            }

        }
        int size = colNames.size();
        for (int i = 0; i < dynamicKeys.size(); i++) {
            colNames.put(size + i, dynamicKeys.get(i));
        }

        for (int i = 0; i < subordinateNames.size(); i++) {
            subColNames.put(size + i, subordinateNames.get(i));
        }
        //看看有多少个日期列 那就要往subColNames塞对应的组的同比值，环比值等表头
        //有几个时间列
        int timeLines = colNames.size() - 4;
        for (int i = 0; i < timeLines; i++) {
            for (int j = 0; j < 3; j++) {
                //求出最大索引
                OptionalInt max = subColNames.keySet().stream()
                        .mapToInt(Integer::intValue)
                        .max();
                int maxIndex = max.getAsInt();
                subColNames.put(++maxIndex, subordinateNames.get(j));
            }
        }

        //创建标题行（表头）
        for (int i = 0; i < dynamicKeys.size(); i++) {
            colNames.put(size + i, dynamicKeys.get(i));
        }
        createHeadRow(workbook, hssfsheet, colNames);
        //表格样式
        // 创建大表头行
        HSSFRow a = hssfsheet.createRow(0);
        a.setHeightInPoints((short) 30);
        HSSFCell headerCell = a.createCell(0);
        // 创建字体样式
        HSSFFont font = workbook.createFont();
        font.setBold(true); // 设置为加粗
        font.setFontHeightInPoints((short) 22); // 设置字体大小
        HSSFCellStyle style = workbook.createCellStyle();
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        headerCell.setCellStyle(style);
        setTitleTime(queryEscalation.getTimes(), headerCell);
        // 合并大表头单元格
        hssfsheet.addMergedRegion(new CellRangeAddress(0, 0, 0, subColNames.size()+fieldMap.size() - 2));

        // 创建小字行
        HSSFRow subtitleRow = hssfsheet.createRow(1);
        HSSFCell subtitleCell = subtitleRow.createCell(0);
        subtitleCell.setCellValue("编制单位：南京鼓楼医院");
        // 合并小字单元格
        hssfsheet.addMergedRegion(new CellRangeAddress(1, 1, 0, subColNames.size()+fieldMap.size() - 2));

        // 设置第一行表头
        Row headerRow = hssfsheet.createRow(2);
        boolean flag = false;
        int maxRowIndex = 0;
        int aaa = 0;
        int bbb = 0;
        for (Integer colIndex : colNames.keySet()) {
            String colName = colNames.get(colIndex);
            //如果colIndex>=3，那么这个表头就要占三个单元格
            Cell cell = null;
            if (flag) {
                bbb++;
                cell = headerRow.createCell(colIndex + 2 * bbb);
            } else {
                cell = headerRow.createCell(colIndex);
            }
            cell.setCellValue(colName);
            if (colIndex >= 3) {
                //时间列占三格
                //区分第一次和后续
                if (flag) {
                    aaa++;
                    hssfsheet.addMergedRegion(new CellRangeAddress(2, 2, colIndex + 2 * aaa, colIndex + 2 * (aaa + 1)));
                    maxRowIndex = colIndex + 2 * (aaa + 1);
                } else {
                    hssfsheet.addMergedRegion(new CellRangeAddress(2, 2, colIndex, colIndex + 2));
                    maxRowIndex = colIndex + 2 * (aaa + 1);
                }
                flag = true;
            }
        }


        // 设置第二行表头 这里循环能不能记录一下第一行colIndex+2的最大值？？
        Row subHeaderRow = hssfsheet.createRow(3);
        for (int colIndex = 0; colIndex <= maxRowIndex; colIndex++) {
            String colName = subColNames.get(colIndex) == null ? "" : subColNames.get(colIndex);
            //如果colIndex>=3，那么这个表头就要占三个单元格
            Cell cell = subHeaderRow.createCell(colIndex);
            //对于非日期列，我们只需要第一行同列合并即可
            if (colIndex < 3) {
                hssfsheet.addMergedRegion(new CellRangeAddress(2, 3, colIndex, colIndex));
            }
            cell.setCellValue(colName);
        }

        HSSFRow hssfRow = null;
        //接下来就是导出数据
        int i = 0;
        if (!CollectionUtils.isEmpty(dataList)) {
            for (Object obj : dataList) {
                hssfRow = hssfsheet.createRow(hssfsheet.getLastRowNum() + 1);
                int dynamicColumnCount = dynamicKeys.size() * 3; // 每个动态列有三个字段
                int totalColumnCount = 3 + dynamicColumnCount; // 固定列 + 动态列的总数

                for (int j = 0; j < totalColumnCount; j++) {
                    HSSFCellStyle basicCellStyle = getBasicCellStyle(workbook);
                    if (j == 0) {
                        // 项目列需要靠左
                        basicCellStyle.setAlignment(HorizontalAlignment.LEFT);
                    }

                    Object value = null;
                    try {
                        if (j < 3) {
                            // 对于固定的前三列，直接取值
                            Field field = fieldMap.get(j);
                            field.setAccessible(true);
                            value = field.get(obj);
                        } else {
                            // 对于动态列，需要特殊处理
                            int dynamicIndex = (j - 3) / 3; // 计算当前动态列的索引
                            String currentDate = dynamicKeys.get(dynamicIndex); // 获取当前动态列对应的日期
                            OptionalInt max = fieldMap.keySet().stream()
                                    .mapToInt(Integer::intValue)
                                    .max();
                            int maxIndex = max.getAsInt();
                            Map<String, HeaderDataDto> dynamicColumnMap = (Map<String, HeaderDataDto>) fieldMap.get(maxIndex).get(obj); // 获取动态列字段的值
                            HeaderDataDto headerDataDto = dynamicColumnMap.get(currentDate); // 获取对应日期的 HeaderDataDto 对象
                            // 根据当前列的偏移量来确定具体是指标值、同比值还是环比值
                            switch ((j - 3) % 3) {
                                case 0:
                                    value = headerDataDto.getIndicator();
                                    break;
                                case 1:
                                    value = headerDataDto.getYoyValue();
                                    break;
                                case 2:
                                    value = headerDataDto.getMomValue();
                                    break;
                                default:
                                    // 可选的其他情况处理
                                    break;
                            }
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }

                    hssfsheet.autoSizeColumn(j);
                    if (j == 0) {
                        setCellValue(value, hssfRow, basicCellStyle, j);
                    } else {
                        setCellValue(value, hssfRow, cellStyle, j);
                    }
                }
                i++;
            }
        }


        // 导出到文件
        try {
            workbook.write(os);
            os.flush();
            os.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(111111);


    }

    private static BufferedOutputStream getBufferedOutputStream(String fileName, HttpServletResponse response) throws Exception {
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
        return new BufferedOutputStream(response.getOutputStream());
    }

    private static void setCellValue(Object value, HSSFRow hssfRow, CellStyle cellStyle, int cellIndex) {
        String valueStr = String.valueOf(value);
        HSSFCell hssfcell = hssfRow.createCell(cellIndex);
        if ("null".equalsIgnoreCase(valueStr)) {
            hssfcell.setCellStyle(cellStyle);
            return;
        }
        if (isNumeric(valueStr)) {
            if (!StringUtils.isEmpty(valueStr)) {
                hssfcell.setCellStyle(cellStyle);
                hssfcell.setCellType(CellType.NUMERIC);
                hssfcell.setCellValue(Double.valueOf(valueStr));
            }
        } else {
            hssfcell.setCellStyle(cellStyle);
            hssfcell.setCellType(CellType.STRING);
            hssfcell.setCellValue(valueStr);
        }
    }

    private static HSSFCellStyle getBasicCellStyle(HSSFWorkbook workbook) {
        HSSFCellStyle hssfcellstyle = workbook.createCellStyle();
        hssfcellstyle.setBorderLeft(BorderStyle.THIN);
        hssfcellstyle.setBorderBottom(BorderStyle.THIN);
        hssfcellstyle.setBorderRight(BorderStyle.THIN);
        hssfcellstyle.setBorderTop(BorderStyle.THIN);
        hssfcellstyle.setAlignment(HorizontalAlignment.CENTER);
        hssfcellstyle.setVerticalAlignment(VerticalAlignment.CENTER);
        hssfcellstyle.setWrapText(true);
        return hssfcellstyle;
    }

    private static void createHeadRow(HSSFWorkbook workbook, HSSFSheet hssfsheet, Map<Integer, String> colNames) {
        //插入标题行
        HSSFRow hssfRow = hssfsheet.createRow(HEAD_ROW_COUNT - 1);
        for (int i = 0; i < colNames.size(); i++) {
            HSSFCell hssfcell = hssfRow.createCell(i);
            hssfcell.setCellStyle(getTitleCellStyle(workbook));
            hssfcell.setCellType(CellType.STRING);
            hssfcell.setCellValue(colNames.get(i));
        }
    }

    private static HSSFCellStyle getTitleCellStyle(HSSFWorkbook workbook) {
        HSSFCellStyle hssfcellstyle = getBasicCellStyle(workbook);
        hssfcellstyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index); // 设置背景色
        hssfcellstyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return hssfcellstyle;
    }

    /**
     * 设置导出报告的时间处理
     *
     * @param times      时间
     * @param headerCell 单元格
     * @author lxk
     */
    public static void setTitleTime(List<String> times, HSSFCell headerCell) {
        String year = "";
        String month = "";
        //分为多年 和 当年
        for (int i = 0; i < times.size(); i++) {
            String time = times.get(i);
            if (time.length() == 4) {
                time = time + "年";
                times.set(i, time);
            } else if(time.length() == 7) {
                year = time.substring(0, 4) + "年";
                month = Integer.parseInt(time.substring(5, 7)) + "月";
                times.set(i, month);
            }else{
                year = time.substring(0, 4) + "年";
                month = Integer.parseInt(time.substring(5, 7)) + "月";
                String day = Integer.parseInt(time.substring(8, 10)) + "号";
                times.set(i, day);
            }
        }
        if (times.get(0).contains("年")) {
            headerCell.setCellValue(String.join(",", times) + "三级公立医院绩效考核数据采集");
        } else if(times.get(0).contains("月")){
            headerCell.setCellValue(year + String.join(",", times) + "三级公立医院绩效考核数据采集");
        }else {
            headerCell.setCellValue(year + month+ String.join(",", times) + "三级公立医院绩效考核数据采集");
        }

    }


    /**
     * 设置导出报告的大标题
     *
     * @param times      时间
     * @param headerCell 单元格
     */
    public static void setTitle(List<String> times, HSSFCell headerCell) {
        String startTime = times.get(0);
        String endTime = times.get(times.size()-1);
        // 将原始日期字符串解析为 LocalDate 对象
        LocalDate startDate = LocalDate.parse(startTime);
        LocalDate endDate = LocalDate.parse(endTime);
        // 定义日期格式化器，将日期格式化为 yyyy年MM月dd日 格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        // 格式化日期
        String sDate = startDate.format(formatter);
        String eDate = endDate.format(formatter);

        headerCell.setCellValue(sDate+"-"+eDate + "三级公立医院绩效考核数据采集");

    }


}
